package br.ufpe.curumim;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class AssyncThreadMain extends AsyncTask<String, Void, MainActivity> {

	byte[] bufImagemTotal;
	long tamanhoArquivo = 0;
	MainActivity mainActivity;

	@Override
	protected MainActivity doInBackground(String... arg0) {

		if (MainActivity.killAll) {
			try {
				this.finalize();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}

	
		mainActivity = MainActivity.mainActivity;

		
		String path = Environment.getExternalStorageDirectory()
				+ File.separator + "test.jpg";
		BufferedOutputStream bufferedOutputStream = null;
		int BUFFER_SIZE = 5120;

		Log.i("assync", "entrou assync task main");

		if (mainActivity.socketCam == null) {
			try {
				mainActivity.socketCam = new Socket(MainActivity.HOST,
						MainActivity.PORTCam);
			} catch (UnknownHostException e2) {
				e2.printStackTrace();
			} catch (IOException e2) {
				e2.printStackTrace();
			}
		}
		if (mainActivity.socketCam != null
				&& mainActivity.socketCam.isConnected()) {
			
			mainActivity.isCamActivated = true;
			
			byte[] buffer = new byte[BUFFER_SIZE];
			InputStream inputStream = null;
			long bytesRead = 0;
			long bytesReaded = 0;
			FileOutputStream fileOutputStream;
			try {
				File file = new File(path);
				if (!file.exists())
					file.createNewFile();
				file.setWritable(true);

				fileOutputStream = new FileOutputStream(path);

				bufferedOutputStream = new BufferedOutputStream(
						fileOutputStream);

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			try {
				inputStream = mainActivity.socketCam.getInputStream();
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			try {
				inputStream.read(buffer, 0, 12);
				String temp = new String(buffer);
				String tamanho = "";
				int index = 0;
				char c;
				do {
					c = temp.charAt(index);
					if (!(c >= 48 && c <= 57))
						break; // deve estar entre '0' = 49 e '9' = 57 da tabela
								// ascii
					tamanho = tamanho.concat(c + "");
					index++;
				} while (true);
				try {
					tamanhoArquivo = Integer.parseInt(tamanho);
				} catch (Exception e) {
					tamanhoArquivo = 0;
				}
			} catch (IOException e2) {
				System.exit(0);
				e2.printStackTrace();
			}
			Log.i("tamanho arquivo bytes: ", "" + tamanhoArquivo);
			bufImagemTotal = new byte[(int) tamanhoArquivo];
			long countBytesImagemTotal = 0;
			try {
				do {
					bytesRead = inputStream.read(buffer);
					bytesReaded += bytesRead;
					Log.i("bytes: ", "" + bytesRead);
					try {
						System.arraycopy(buffer, 0, bufImagemTotal,
								(int) countBytesImagemTotal, (int) bytesRead);
					} catch (Exception e) {
						e.printStackTrace();
					}
					countBytesImagemTotal += bytesRead;
					bufferedOutputStream.write(buffer, 0, (int) bytesRead);
				} while (bytesReaded < tamanhoArquivo);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		bm = BitmapFactory.decodeByteArray(bufImagemTotal, 0,
				(int) tamanhoArquivo);
		try {
			bufferedOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	Bitmap bm;

	@Override
	protected void onPostExecute(MainActivity result) {
		super.onPostExecute(result);
		Log.i("sucesso", "on post execute");
		mainActivity.iv_cam.setImageBitmap(bm);
		mainActivity.handlerCam.sendEmptyMessage(0);
	}
}
